﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data.OracleClient;


public partial class Account_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string userid = ((System.Web.UI.WebControls.Login)sender).UserName;
        string uid = userid + "@petrochina.com.cn";

        string pwd = ((System.Web.UI.WebControls.Login)sender).Password;

        string sPath = "LDAP://ptr.petrochina/DC=ptr,DC=petrochina"; //"WinNT://ptr";
        System.DirectoryServices.DirectoryEntry entry1 = new System.DirectoryServices.DirectoryEntry(sPath, uid, pwd, System.DirectoryServices.AuthenticationTypes.ServerBind);

        System.DirectoryServices.DirectorySearcher myDirectorySearcher = new System.DirectoryServices.DirectorySearcher(entry1);

        myDirectorySearcher.Filter = "(sAMAccountName=" + userid + ")";

        myDirectorySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;

        try
        {
            string nameCN = myDirectorySearcher.FindOne().Properties["cn"][0].ToString();
            string DepartmentFullName = myDirectorySearcher.FindOne().Properties["department"][0].ToString();
            string depname = DepartmentFullName.Substring(6);

            //判断该用户是否为授权用户，即在数据库中检索是否有该用户的邮箱名，因为已经经过LDAP的审核，所以中文姓名可以作为唯一标识。

            string connStr = WebConfigurationManager.ConnectionStrings["ConnectionStringForOracle"].ConnectionString;
            string commStr = "select count(USERID) from BC_USER where USERID='" + userid + "'";

            OracleConnection conn = new OracleConnection(connStr);
            OracleCommand comm = new OracleCommand(commStr, conn);

            conn.Open();
            string count = comm.ExecuteScalar().ToString();

            conn.Close();
            comm.Dispose();

            if (count == "1")
            {
                e.Authenticated = true;
                LoginUser.UserName = nameCN;
                Session["DepartmentName"] = depname;
            }
            else
            {
                LoginUser.FailureText = "请联系管理员给您授权。";
            }
        }
        catch
        {
            e.Authenticated = false;
            LoginUser.FailureText = "请确定您输入了正确的中石油邮箱帐户和密码。";
            //return null;
        }
        finally
        {
            myDirectorySearcher.Dispose();
            entry1.Dispose();
        }
    }
}
